$(function () {
    layui.use(['table', 'layer', 'laytpl', 'form', 'step', 'util'], function () {
        var table = layui.table,
            layer = layui.layer,
            laytpl = layui.laytpl,
            form = layui.form,
            step = layui.step,
            util = layui.util;
        // 记录各个新增项
        let areaSelected = null;
        let gatewaySelected = null;
        let readerCodeSelected = null;
        let deviceSelected = null;
        // 区域layer index
        let areaLayerIdx = null;
        // 当前在哪一步
        let currentStep = 1;
        step.render({
            elem: '#stepForm',
            filter: 'stepForm',
            width: '100%', //设置容器宽度
            stepWidth: '100%',
            height: '100%',
            stepItems: [{
                title: '区域设置'
            }, {
                title: '网关设置'
            }, {
                title: '仪表设置'
            }, {
                title: '设备设置'
            }, {
                title: '完成'
            }]
        });

        getAreaData();

        form.verify({
            ip: function(value, item) {
                let patternIP = /((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}/g;
                if(value == ''){
                    return '必填项不能为空'
                }else if(!patternIP.test(value)){
                    return '非法的IP地址'
                }
            },
            port: function(value, item) {
                let patternPort = /^[1-9]+[0-9]*$/
                if(value == ''){
                    return '必填项不能为空'
                }else if(!patternPort.test(value)){
                    return '端口号需为正整数'
                }
            },
            readerCode: function (value, item) {
                let patternPort = /^[1-9]+[0-9]*$/
                if(value == ''){
                    return '必填项不能为空'
                }else if(!patternPort.test(+value)){
                    return '仪表识别码格式不正确'
                }else{
                    let arr = [2,4,8,14];
                    if(arr.indexOf(value.length) === -1){
                        return '仪表识别码长度不正确'
                    }
                }
            }
        });

        $("body").keydown(function(e){
            console.log(currentStep)
            if(e.keyCode == 13){
                switch (currentStep) {
                    case 1:
                        $('button[lay-filter="stepToGateway"]').click();
                        break;
                    case 2:
                        $('button[lay-filter="add-gateway-box"]').click();
                        break;
                    case 3:
                        $('button[lay-filter="add-readerCode-box"]').click();
                        break;
                    case 4:
                        $('button[lay-filter="add-device-box"]').click();
                        break;
                    case 5:
                        currentStep = 1;
                        break;
                }
                return false;
            }
        });

        // 进入网关
        form.on('submit(stepToGateway)', function (data) {
            currentStep = 2;
            layer.close(areaLayerIdx);
            step.next('#stepForm');
            areaSelected = {
                areaId: $('.areaMenu option:selected').val(),
                areaName: $('.areaMenu option:selected').text()
            };
            $('.area-selected').text(areaSelected.areaName);
            $('.area-selected').attr('areaId' , areaSelected.areaId);
            // getGatewayData();
            return false;
        });

        // 进入仪表识别码
        form.on('submit(stepToReaderCode)', function (data) {
            currentStep = 3;
            step.next('#stepForm');
            $('.gateway-selected').text(gatewaySelected.ip);
            $('.gateway-selected').attr('gatewayId' , gatewaySelected.ip);
            return false;
        });

        // 进入设备
        form.on('submit(stepToDevice)', function (data) {
            currentStep = 4;
            step.next('#stepForm');
            $('.readerCode-selected').text(readerCodeSelected.readerCode);
            form.val('add-device-box', {
                areaId: areaSelected.areaId,
                areaName: areaSelected.areaName,
                ip: gatewaySelected.ip,
                readerCode: readerCodeSelected.readerCode
            });
            return false;
        });

        form.on('submit(stepToComplete)', function (data) {
            step.next('#stepForm');
            deviceSelected.deviceTypeCodeStr = deviceSelected.deviceTypeCode == 0? '电表' : '水表';
            for(let k in deviceSelected){
                $('.complete-box ul span[data-field="'+ k +'"]').text(deviceSelected[k]);
            }
            // 设备添加成功 => 清空各表单、清空变量
            $('.deviceReset').click();
            $('.gatewayReset').click();
            $('.readerCodeReset').click();
            areaSelected= null;
            gatewaySelected= null;
            readerCodeSelected= null;
            deviceSelected = null;
            currentStep = 1;
            return false;
        });

        $('.pre').click(function () {
            currentStep--;
            step.pre('#stepForm');
        });

        $('.next').click(function () {
            step.next('#stepForm');
        });

        /* 区域 */
        function getAreaData(item) {
            $.ajax({
                type: "post",
                url: ctx + "/areaManger/areaAll.do",
                data: {},
                dataType: "json",
                success: function (data) {
                    let opt = '<option value="">请选择</option>';
                    for (let i = 0; i < data.length; i++) {
                        opt += `<option value="${data[i].areaId}">${data[i].areaName}</option>`;
                    }
                    $('.step-area .areaMenu').html(opt);
                    if(item){
                        form.val('step-area', item);
                    }
                    form.render('select');
                }
            });
        }
        function addArea(data, areaLayerIdx) {
            $.ajax({
                url: ctx + "/areaManger/insertArea.do",
                type: "post",
                data: data,
                dataType: "json",
                success: function (res) {
                    if (res.code == '000000') {
                        getAreaData(data);
                        layer.close(areaLayerIdx);
                    } else {
                        layer.alert(res.message);
                    }
                }
            });
        }
        $('#area-btn').click(function () {
            areaLayerIdx = layer.open({
                type: 1,
                title: "新增区域",
                closeBtn: 1,
                anim: 0,
                shade: 0,
                area: 'auto',
                content: $('#area-layer-tpl').html()
            });
            form.on('submit(add-area-box)', function (res) {
                addArea(res.field, areaLayerIdx);
                return false;
            });
            $(".add-area-box button[type='cancel']").click(function () {
                layer.close(areaLayerIdx);
                return false;
            });
        });

        /* 网关 */
        function addGateway(data) {
            $.ajax({
                type: "GET",
                url: ctx + "/gatewayManage/add.do",
                data: data,
                dataType: "json",
                success: function (result) {
                    if (result.code == '000000') {
                        addReaderCode(readerCodeSelected);
                    } else {
                        layer.alert(result.message);
                    }
                }
            });
        }

        // ip简称赋值
        $('input#ip').bind('blur', function () {
            // ip格式验证
            let pattern = /((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}/g;
            let val = $(this).val();
            if(pattern.test(val)){
                $('input[name="gatewayName"]').val(sliceIp(val))
            }else{
                layer.tips('非法的IP地址', '#ip',{
                    tips: [2, '#F56C6C'],time: 2000
                });
            }
        });

        form.on('submit(add-gateway-box)', function (res) {
            // addGateway(res.field);
            gatewaySelected = res.field;
            // $('.gatewayReset').click();
            $('.stepToReaderCode').click();
            return false;
        });
        $(".add-gateway-box button[type='cancel']").click(function () {
            return false;
        });

        /* 仪表识别码 */
        function addReaderCode(data) {
            data.ip = gatewaySelected.ip;
            $.ajax({
                type: "GET",
                url: ctx + "/sensorManage/add.do",
                data: data,
                dataType: "json",
                success: function (result) {
                    if (result.code == '000000') {
                        addDevice(deviceSelected);
                    } else {
                        layer.alert(result.message);
                    }
                }
            });
        }
        form.on('submit(add-readerCode-box)', function (res) {
            readerCodeSelected = res.field;
            $('.stepToDevice').click();
            return false;
        });
        $(".add-readerCode-box button[type='cancel']").click(function () {
            return false;
        });

        /* 设备 */
        function addDevice(data) {
            $.ajax({
                type: "GET",
                url: ctx + "/meterManager/add.do",
                data: data,
                dataType: "json",
                success: function (result) {
                    if (result.code == '000000') {
                        // 进入下一步
                        $('.stepToComplete').click();
                    } else {
                        layer.alert(result.message);
                    }
                }
            });
        }

        form.on('submit(add-device-box)', function (res) {
            deviceSelected = res.field;
            addGateway(gatewaySelected);
            return false;
        });
        $(".add-param button[type='cancel']").click(function () {
            return false;
        });

        // ip简称截取
        function sliceIp(ip){
            let arr = ip.split('.');
            if(arr.length == 4){
                return  arr[arr.length - 2] + '.' + arr[arr.length - 1];
            }else{
                return ''
            }
        }

    });
});
